import CreateModal from '@/pages/Admin/Visitor/components/CreateModal';
import UpdateModal from '@/pages/Admin/Visitor/components/UpdateModal';
import { deleteVisitorUsingPost, listVisitorByPageUsingGet } from '@/services/backend/visitorController';
import { PlusOutlined, ExportOutlined } from '@ant-design/icons'; // 添加导出图标
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import { Button, message, Space, Typography, Statistic, Table } from 'antd';
import React, { useRef, useState } from 'react';
import * as XLSX from 'xlsx'; // 导入Excel库

/**
 * 顾客管理页面
 *
 * @constructor
 */
const VisitorAdminPage: React.FC = () => {
  // 是否显示新建窗口
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  // 是否显示更新窗口
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  // 当前用户点击的数据
  const [currentRow, setCurrentRow] = useState<API.Visitor>();
  // 存储消费金额总和
  const [saleTotal, setSaleTotal] = useState<number>(0);
  // 存储表格数据
  const [tableData, setTableData] = useState<API.Visitor[]>([]);

  /**
   * 删除节点
   *
   * @param row
   */
  const handleDelete = async (row: API.Visitor) => {
    const hide = message.loading('正在删除');
    if (!row) return true;
    try {
      await deleteVisitorUsingPost({
        id: row.id as any,
      });
      hide();
      message.success('删除成功');
      actionRef?.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('删除失败，' + error.message);
      return false;
    }
  };

  /**
   * 导出Excel文件
   */
  const exportToExcel = () => {
    if (tableData.length === 0) {
      message.warning('没有数据可导出');
      return;
    }

    // 准备导出的数据（只包含需要的列）
    const exportData = tableData.map(item => ({
      姓名: item.visitorName,
      电话: item.visitorPhone,
      生日: item.visitorBirthday,
      充值金额: item.visitorTopUp,
      消费金额打折前: item.visitorConsume,
      酒水: item.visitorAlcohols,
      饮料: item.visitorDrinks,
      菜品: item.visitorMeals,
      消费金额打折后: item.visitorSale,
      备注: item.visitorDescription,
      活跃度: item.visitorActivity === 0 ? '活跃' : item.visitorActivity === 1 ? '沉默' : '流失',
      是否VIP: item.visitorVip === 1 ? '是' : '否',
      创建时间: item.createTime,
      更新时间: item.updateTime
    }));

    // 创建工作簿和工作表
    const worksheet = XLSX.utils.json_to_sheet(exportData);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, '顾客数据');

    // 生成Excel文件并下载
    XLSX.writeFile(workbook, `顾客数据_${new Date().toLocaleString().replace(/[/:\\]/g, '_')}.xlsx`);
    message.success('导出成功');
  };

  /**
   * 表格列配置
   */
  const columns: ProColumns<API.Visitor>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'text',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '姓名',
      dataIndex: 'visitorName',
      valueType: 'text',
    },
    {
      title: '电话',
      dataIndex: 'visitorPhone',
      valueType: 'text',
    },
    {
      title: '第二电话',
      dataIndex: 'visitorSecondPhone',
      valueType: 'text',
    },
    {
      title: '生日',
      dataIndex: 'visitorBirthday',
      valueType: 'date',
    },
    {
      title: '充值金额',
      dataIndex: 'visitorTopUp',
      valueType: 'text',
    },
    {
      title: '消费金额(打折前)',
      dataIndex: 'visitorConsume',
      valueType: 'text',
    },
    {
      title: '酒水',
      dataIndex: 'visitorAlcohols',
      valueType: 'text',
    },
    {
      title: '饮料',
      dataIndex: 'visitorDrinks',
      valueType: 'text',
    },
    {
      title: '菜品',
      dataIndex: 'visitorMeals',
      valueType: 'text',
    },
    {
      title: '消费金额(打折后)',
      dataIndex: 'visitorSale',
      valueType: 'text',
    },
    {
      title: '余额',
      dataIndex: 'visitorBalance',
      valueType: 'text',
      hideInSearch: true,
      hideInForm:true,
    },
    {
      title: '备注',
      dataIndex: 'visitorDescription',
      valueType: 'text',
    },
    {
      title: '活跃度',
      dataIndex: 'visitorActivity',
      valueEnum: {
        0: {
          text: '活跃',
        },
        1: {
          text: '沉默',
        },
        2: {
          text: '流失',
        },
      },
    },
    {
      title: '是否VIP',
      dataIndex: 'visitorVip',
      valueEnum: {
        0: {
          text: '不是',
        },
        1: {
          text: '是',
        },
      },
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '更新时间',
      sorter: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space size="middle">
          <Typography.Link
            onClick={() => {
              setCurrentRow(record);
              setUpdateModalVisible(true);
            }}
          >
            修改
          </Typography.Link>
          <Typography.Link type="danger" onClick={() => handleDelete(record)}>
            删除
          </Typography.Link>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.Visitor>
        headerTitle={'顾客管理'}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        // 添加汇总行
        summary={() => (
          <Table.Summary fixed>
            <Table.Summary.Row>
              <Table.Summary.Cell index={0} colSpan={6}>
                <Statistic
                  title="消费金额(打折后) 总和"
                  value={saleTotal}
                  precision={2}
                  valueStyle={{ color: '#cf1322', fontWeight: 'bold' }}
                />
              </Table.Summary.Cell>
            </Table.Summary.Row>
          </Table.Summary>
        )}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCreateModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
          // 添加导出按钮
          <Button
            key="export"
            type="default"
            onClick={exportToExcel}
            icon={<ExportOutlined />}
          >
            导出Excel
          </Button>
        ]}
        request={async (params, sort, filter) => {
          const sortField = Object.keys(sort)?.[0];
          const sortOrder = sort?.[sortField] ?? undefined;
          const { data, code } = await listVisitorByPageUsingGet({
            ...params,// 这里包含了搜索栏的所有参数
            sortField,
            sortOrder,
            ...filter,
          } as API.VisitorQueryRequest);

          if (code === 0 && data) {
            // 存储表格数据用于导出
            setTableData(data.records || []);

            // 计算消费金额(打折后)总和
            if (data.records && data.records.length > 0) {
              const total = data.records.reduce((sum: number, item: API.Visitor) => {
                // 将字符串转换为数字，无法转换的视为0
                const saleValue = parseFloat(item.visitorSale as string) || 0;
                return sum + saleValue;
              }, 0);
              setSaleTotal(total);
            } else {
              setSaleTotal(0);
            }
          }

          return {
            success: code === 0,
            data: data?.records || [],
            total: Number(data?.total) || 0,
          };
        }}
        columns={columns}
      />
      <CreateModal
        visible={createModalVisible}
        columns={columns}
        onSubmit={() => {
          setCreateModalVisible(false);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setCreateModalVisible(false);
        }}
      />
      <UpdateModal
        visible={updateModalVisible}
        columns={columns}
        oldData={currentRow}
        onSubmit={() => {
          setUpdateModalVisible(false);
          setCurrentRow(undefined);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setUpdateModalVisible(false);
        }}
      />
    </PageContainer>
  );
};
export default VisitorAdminPage;
